<template>
  <Top-Page class="container">
    <!-- 搜索框 -->
    <view class="search-box" v-show="searchShow">
      <input v-model="searchText" type="text" placeholder="搜索" @input="onSearch" class="search-inp" />
      <view @click="onCancel" class="search-cancel">{{ searchText ? '清空' : '返回' }}</view>
    </view>

    <!-- 内容类型选择 -->
    <view class="content-type-selector" v-show="contentTypesShow">
      <view class="type-title">搜索指定内容</view>

      <view class="type-wrap">
        <view class="type-tiem" v-for="item in contentTypes" @click.stop="searchType(item)" :key="item">
          {{ item }}
        </view>
      </view>
    </view>

    <view v-if="contentType === '日期'" class="content-type__date">
      <NavBar title="按日期查找" left-arrow @click-left="reset" />
      <scroll-view class="scroll-view" ref="scrollView" scroll-y="true" :scroll-anchoring="true">
        <view class="date-picker">
          <view class="data-wrap" v-for="(monthDays, year) in dateData">
            <template v-for="(days, month) in monthDays">
              <view class="year-month-item">{{ year }}年{{ month }}月</view>
              <view class="day-wrap">
                <view
                  v-for="day in getDaysInMonth(year, month)"
                  @click.stop="lookMsg(year, month, day, days)"
                  :class="['day', getDayClass(day, year, month)]"
                >
                  {{ day }}
                </view>
              </view>
            </template>
          </view>
        </view>
      </scroll-view>
    </view>
    <view v-else-if="contentType != '全部'" class="content-type__other">
      <NavBar :title="contentType" left-arrow @click-left="reset" />
    </view>

    <!-- 消息列表 -->
    <scroll-view
      scroll-y
      :class="['message-list', { 'message-list-bg': messages.length }]"
      @scrolltolower="scrolltolower"
    >
      <template v-for="(item, index) in messages" :key="index" @click.stop="toMsg('text', item)">
        <view class="message-item__all" v-if="contentType === '全部'">
          <image class="message-avatar" :src="item.fromUser.avatar" mode="aspectFill" />

          <view class="item-right">
            <view class="item-title">
              <view class="item-realname">{{ item.fromUser.realname }}</view>

              <!-- <view class="item-time">{{ formatTime(item.sendTime) }}</view> -->
            </view>

            <view class="item-content text-one">
              <mp-html
                container-style="overflow: hidden;display:inline;white-space: pre-wrap"
                :content="emojiToHtml(item.content, item)"
              />
            </view>
          </view>
        </view>

        <view
          v-else-if="contentType === '图片与视频'"
          class="message-item__image_video"
          @click="previewImage(item.content)"
        >
          <image class="item-image_video" v-if="item.type === 'image'" mode="aspectFill" :src="item.content" />
          <video class="item-image_video" v-if="item.type === 'video'" :src="item.content" />
        </view>

        <view class="message-item__file" v-else-if="contentType == '文件'">
          <view class="message-item__file-heard">
            <view class="heard-left">
              <image class="heard-left-avatar" :src="item.fromUser.avatar" mode="aspectFill" />
              <view class="heard-left-realname">{{ item.fromUser.realname }}</view>
            </view>
            <view class="heard-right__time">{{ formatTime(item.sendTime) }}</view>
          </view>
          <view
            class="file-card bg-white radius-10 im-flex im-justify-content-start pd-10 im-align-items-center"
            @tap="preview(item)"
          >
            <view class="file-icon cuIcon-text f-36"></view>
            <view class="im-flex im-columns ml-10">
              <view class="text-overflow file-name">{{ item.fileName }}</view>
              <view class="text-gray file-size f-12">{{ fileSize(item.fileSize) }}</view>
            </view>
          </view>
        </view>

        <view v-else-if="contentType === '音乐与音频'" class="message-item__audio">
          <view @click.stop="closeMusic(item.content)">
            <sy-audio
              ref="audio"
              :src="item.content"
              audioCover=""
              subheading=""
              :audioTitle="item.fileName"
              :key="item.id"
            ></sy-audio>
          </view>
        </view>
      </template>

      <view v-if="finished" class="finished-1">没有更多了</view>
    </scroll-view>
  </Top-Page>
</template>

<script>
import NavBar from '@/components/NavBar/NavBar.vue';
import { navBack, debounce } from '@/utils/utils.js';
import emoji from '@/utils/emoji.js';
export default {
  components: { NavBar },
  data() {
    return {
      navBack: navBack,
      finished: false,
      query: {},
      searchText: '', //搜索框
      searchShow: true,
      //指定搜索内容
      contentTypesShow: true,
      contentType: '全部',
      contentTypes: ['图片与视频', '文件', '音乐与音频'], //'日期',
      lookTime: '', //查询的时间
      //文本搜索的结果
      messages: [],
      page: 0,
      //日期结果
      dateData: {},
      //表情包
      emojiMap: [],
      innerAudioContext: null,
      autoplay: false
    };
  },
  watch: {
    searchText(t) {
      this.contentTypesShow = !t;
      this.messages.length = 0;
      this.page = 0;
      this.finished = false;
    }
  },
  created: function () {
    let emojiMap = [];
    // 解析所有表情
    emoji.forEach(function (item) {
      let child = item.children;
      if (child.length > 0) {
        child.forEach(function (val) {
          let name = val.name;
          let src = val.src;
          emojiMap[name] = src;
        });
      }
    });
    this.emojiMap = emojiMap;

    this.innerAudioContext = uni.createInnerAudioContext();
  },
  onLoad(options) {
    Object.assign(this.query, options);

    if (Number(options.is_group)) {
      this.contentTypes.splice(3, 0, '群成员');
    }
  },
  methods: {
    //播放音乐
    closeMusic(src) {
      this.autoplay = !this.autoplay;
      this.innerAudioContext.autoplay = this.autoplay;
      this.innerAudioContext.src = src;
      this.innerAudioContext.onPlay(() => {
        console.log('开始播放');
      });
      this.innerAudioContext.onError((res) => {
        uni.showToast({
          title: '当前音频异常',
          icon: 'none'
        });
      });
    },
    // 文件预览
    preview(item) {
      let audioExt = ['mp3', 'wav', 'acc'];
      let extension = item.content.split('.').pop().toLowerCase();
      if (audioExt.includes(extension)) {
        uni.showToast({
          title: '音频文件无法预览',
          icon: 'exception'
        });
        // this.curMsg = item;
        // this.modelName = 'musicPlay';
        return;
      }
      // #ifdef APP-PLUS || MP-WEIXIN
      let exts = ['doc', 'xls', 'ppt', 'pdf', 'docx', 'xlsx', 'pptx'];
      if (exts.includes(extension)) {
        console.log('满足');
        uni.showLoading({ title: '文件加载中' });
        uni.downloadFile({
          url: item.content,
          success: function (res) {
            uni.hideLoading();
            var filePath = res.tempFilePath;
            uni.openDocument({
              filePath: filePath,
              showMenu: true,
              success: function (res) {
                console.log('打开文档成功');
              }
            });
          },
          fail() {
            uni.hideLoading();
          }
        });
      } else {
        uni.showToast({
          title: '该文件不支持预览！',
          icon: 'none'
        });
      }
      // #endif

      // #ifdef H5
      const tempLink = document.createElement('a');
      tempLink.style.display = 'none';
      tempLink.href = item.download;
      tempLink.setAttribute('download', item.fileName);
      tempLink.setAttribute('target', '_blank');
      document.body.appendChild(tempLink);
      tempLink.click();
      document.body.removeChild(tempLink);
      // #endif
    },
    fileSize(size) {
      return this.$util.getFileSize(size);
    },
    //图片预览
    previewImage(current) {
      const urls = this.messages.filter((item) => item.type === 'image').map((item) => item.content);
      console.log(urls);
      uni.previewImage({
        current: current,
        urls: urls
      });
    },
    toMsg(type, item) {
      const data = {
        history: true,
        type: type
      };

      type === 'text' ? (data['msg_id'] = item.msg_id) : (data['date'] = this.lookTime);

      const pages = getCurrentPages();
      const beforePage = pages[pages.length - 3];
      beforePage.$vm.historyMsg(data);

      this.navBack(2);
    },
    //查看指定日期的消息记录
    lookMsg(year, month, day, days) {
      if (!days.includes(String(day))) {
        return;
      }
      this.lookTime = `${year}-${month}-${day}`;
      this.toMsg('date', {});
    },
    // 自动解析消息中的表情
    emojiToHtml(str, item) {
      /**
       * item.age_max 不存在年龄或者最大限制年龄为0 表示不限制
       * item.sex == 3 表示不限制
       */
      if (Number(item.is_group) == 1) {
        if (!!item.age_max || item.sex != 3) {
          if (item.sex != this.userInfo.sex) {
            if (item.sex == this.userInfo.sex && this.userInfo.age < item.age_min && this.userInfo.age > item.age_max) {
              item.unread = item.unread - 1;
              return;
            }
          }
        }
      }

      if (!str) {
        return;
      }

      let st = '';

      if (item.type === 'location') {
        st = '[位置信息]';
      } else if (item.type === 'usercard') {
        st = '[名片]';
      } else if (item.type === 'connectdragon') {
        st = `[接龙]`;
      }
      //定位信息
      else if (str.address) {
        st = str.address;
      }
      //正常的表情包
      else {
        let emojiMap = this.emojiMap;
        st = str.replace(/\[!(\w+)\]/gi, function (str, match) {
          var file = match;
          return emojiMap[file]
            ? '<img class=\'mr-5\' style="width:18px;height:18px" emoji-name="'
                .concat(match, '" src="')
                .concat(emojiMap[file], '" />')
            : '[!'.concat(match, ']');
        });
      }
      return st;
    },
    //根据年月判断当月有多少天
    getDaysInMonth(year, month) {
      return new Date(year, month, 0).getDate();
    },
    //判断后台数据是否有当天
    isActiveDay(day, year, month) {
      const monthDays = this.dateData[year][month.toString()];
      return monthDays && monthDays.includes(day.toString());
    },
    //判断是不是今天
    isToday(year, month, day) {
      const today = new Date();
      return today.getFullYear() === year && today.getMonth() + 1 === month && today.getDate() === day;
    },
    //添加样式
    getDayClass(day, year, month) {
      const isActive = this.isActiveDay(day, year, month);
      const isToday = this.isToday(Number(year), Number(month), Number(day));

      return {
        active: isActive,
        today: isActive && isToday
      };
    },
    onSearch: debounce(function () {
      if (!this.searchText) return;
      this.msglog();
    }),
    //页面返回
    onCancel() {
      if (this.searchText) {
        this.searchText = '';
      } else {
        this.navBack();
      }
    },
    //指定消息的返回重置
    reset() {
      this.messages.length = 0;
      this.page = 0;
      this.finished = false;
      this.contentTypesShow = !this.contentTypesShow;
      this.searchShow = !this.searchShow;
      this.contentType = '全部';
    },
    searchType(type) {
      this.contentTypesShow = !this.contentTypesShow;
      this.searchShow = !this.searchShow;
      this.contentType = type;

      if (type === '日期') {
        this.msglogdatelist();
      } else {
        this.msglog();
      }
    },
    msglogdatelist() {
      const data = {
        is_group: this.query.is_group,
        toContactId: this.query.id
      };

      this.$api.msgApi.msglogdatelist(data).then((res) => {
        console.log(res);
        if (res.code === 0) {
          this.dateData = res.data;
        }
      });
    },
    msglog() {
      const data = {
        type: this.contentType,
        text: this.searchText,
        is_group: this.query.is_group,
        toContactId: this.query.id,
        date: this.lookTime,
        page: ++this.page,
        limit: 12
      };

      this.$api.msgApi.msglog(data).then((res) => {
        if (res.code === 0) {
          const data = res.data ?? [];

          if (data.length < 12) {
            this.finished = true;
          }

          data.reverse();
          this.messages.push(...data);
        }
      });
    },
    scrolltolower() {
      if (this.finished) return;
      this.msglog();
    },
    formatTime(timestamp) {
      return this.$util.timeFormat(timestamp);
    }
  }
};
</script>

<style lang="scss">
.container {
  width: 100%;
  min-height: 100vh;
  background-color: #f4f4f4;
}

:deep .nav-bar {
  position: relative !important;
}

//搜索框
.search-box {
  width: 94%;
  margin-left: 3%;
  margin-top: 20rpx;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  display: flex;
  flex-direction: row;
  align-items: center;

  .arrow-left {
    flex-shrink: 0;
  }

  .search-inp {
    background-color: #fff;
    padding: 10rpx;
    margin-right: 16rpx;
  }

  .search-cancel {
    color: #0064b0;
    flex-shrink: 0;
  }
}

.search-box input {
  width: 100%;
  height: 60rpx;
  padding: 0 20rpx;
}

//搜索指定内容
.content-type-selector {
  margin-top: 100rpx;
  text-align: center;

  .type-title {
    color: #999;
    font-size: calc(24rpx * var(--amplified_base));
    letter-spacing: 2rpx;
  }

  .type-wrap {
    width: 80%;
    margin-left: 10%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    flex-direction: row;
    color: #0064b0;

    .type-tiem {
      width: 33.33%;
      margin-top: 60rpx;
    }
  }
}

.message-list-bg {
  background-color: #fff;
  height: calc(100vh - 100rpx);
}

.message-list {
  max-height: 100vh;

  :deep .uni-scroll-view-content {
    box-sizing: border-box;
    padding: 0 25rpx;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    align-items: center;
    align-content: flex-start;
  }

  //音频音频
  .message-item__audio {
    margin-top: 20rpx;
  }

  //图片视频
  .message-item__image_video {
    width: 175rpx;
    height: 175rpx;

    video,
    image {
      width: 100%;
      height: 100%;
    }
  }

  //文件
  .message-item__file {
    width: 100%;
    margin-top: 20rpx;

    .message-item__file-heard {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .heard-left {
        display: flex;
        align-items: center;

        .heard-left-avatar {
          width: 50rpx;
          height: 50rpx;
          border-radius: 8rpx;
        }
        .heard-left-realname {
          margin-left: 20rpx;
        }
      }

      .heard-right__time {
        color: #aaa;
      }
    }

    .file-card {
      width: 100%;
    }
  }

  .message-item__all {
    width: 100%;
    // padding: 0 30rpx;
    display: flex;
    align-items: center;
  }

  .message-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 12rpx;
    flex-shrink: 0;
  }

  .item-right {
    padding: 30rpx 0;
    margin-left: 20rpx;
    flex: 1;
    border-bottom: 1rpx solid #f4f4f4;

    .item-title {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .item-realname {
        color: #666;
      }

      .item-time {
        color: #aaa;
      }
    }

    .item-content {
      margin-top: 12rpx;
    }
  }
}

//日期
.date-picker {
  margin-bottom: 100rpx;
  color: #aaa;

  .data-wrap {
    margin-top: 40rpx;
  }

  .year-month-item {
    border-bottom: 1rpx solid #ccc;
    line-height: 2;
    padding: 0 60rpx;
  }

  .day-wrap {
    padding: 0 60rpx;
    display: flex;
    flex-wrap: wrap;

    .day {
      width: 50rpx;
      height: 50rpx;
      line-height: 50rpx;
      text-align: center;
      margin: 20rpx;
    }

    .active {
      color: #000;
    }

    .today {
      background-color: #309446;
      border-radius: 50%;
      color: #fff;
    }
  }
}

.finished-1 {
  bottom: 20rpx;
  width: 100%;
  padding: 50rpx;
  text-align: center;
  color: #999;
}
</style>
